/*
 * Copyright (C) 2018 guomw.Inc. All rights reserved.
 * 项目名称： mysite
 * 文件名称： roles.js
 * Date：18-9-20 上午10:06
 * Author: guomw
 */
$(function () {
    rolesHandler.init();
    rolesHandler.initMenu();
});

/**
 * 角色
 */
var rolesHandler = {
    localData: [],
    authority: "",
    menuList: [],
    menusTemplate: $("#menus_template").html(),
    menusbtnTemplate: $("#menus_btn_template").html(),
    init: function () {
        var self = this;
        hotUtil.loading.show();
        hotUtil.ajaxCall("/sys/ajax/rolelist", {}, function (ret) {
            hotUtil.loading.close();
            if (ret.resultCode === 1) {
                var appendHtml = '';
                self.localData = ret.data;
                $.each(ret.data, function (i, item) {
                    var tempHtml = $("#table-content-template").html();
                    tempHtml = tempHtml.replace(/{index}/gm, i + 1);
                    tempHtml = tempHtml.replace(/{roleId}/gm, item.roleId);
                    tempHtml = tempHtml.replace(/{roleName}/gm, item.roleName);
                    tempHtml = tempHtml.replace(/{roleType}/gm, item.roleType == -1 ? "系统内置角色" : "自定义");
                    tempHtml = tempHtml.replace(/{enable}/gm, item.enable ? "启用" : "禁用");
                    if (item.roleType != -1) {
                        var btnTempHtml = self.menusbtnTemplate.replace("{clickMethod}", "rolesHandler.setPower(" + item.roleId + ")").replace("{title}", "设置权限").replace(/{target}/gm, "#addRolePowerModal");
                        btnTempHtml += self.menusbtnTemplate.replace("{clickMethod}", "rolesHandler.edit(" + item.roleId + ")").replace("{title}", "编辑").replace(/{target}/gm, "#addRoleModal");
                        btnTempHtml += self.menusbtnTemplate.replace("{clickMethod}", "rolesHandler.delete(" + item.roleId + ")").replace("{title}", "删除").replace(/{target}/gm, "");
                        btnTempHtml += self.menusbtnTemplate.replace("{clickMethod}", "rolesHandler.setEnable(" + item.roleId + ")").replace("{title}", item.enable ? "禁用" : "启用").replace(/{target}/gm, "");
                        tempHtml = tempHtml.replace(/{btnItems}/, btnTempHtml);
                    }
                    else {
                        tempHtml = tempHtml.replace(/{btnItems}/, "");
                    }
                    appendHtml += tempHtml;
                });
                $("#table-content").html(appendHtml);
            }
        });
    },
    getModel: function (roleId) {
        var result = {};
        $.each(this.localData, function (i, item) {
            if (item.roleId === roleId) {
                result = item;
                return false;
            }
        });
        return result;
    },
    setModel: function (roleId, authority) {
        var self = this;
        $.each(self.localData, function (i, item) {
            if (item.roleId === roleId)
                self.localData[i].authority = authority;
            return;
        });
    },
    edit: function (roleId) {
        var roleName = "";
        if (roleId > 0) {
            var data = this.getModel(roleId);
            if (data != null) {
                roleName = data.roleName
            }
            else {
                roleId = 0;
            }
        }
        $("#modal-role-title").text(roleId > 0 ? "编辑角色" : "添加角色")
        $("#roleId").val(roleId);
        $("#roleName").val(roleName);
    },
    delete: function (roleId) {
        swal({
            title: "您确定要删除这条信息吗",
            text: "删除后将无法恢复，请谨慎操作！",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "删除",
            closeOnConfirm: false
        }, function () {
            hotUtil.loading.show();
            hotUtil.ajaxCall("/sys/ajax/deleterole", {
                roleId: roleId
            }, function (ret) {
                hotUtil.loading.close();
                if (ret.resultCode === 1) {
                    rolesHandler.init();
                    swal("删除成功！", "您已经永久删除了这条信息。", "success");
                }
                else {
                    swal("删除失败！", ret.resultMsg, "error");
                }
            });
        });
    },
    btnSubmit: function () {
        if (hotUtil.isNullOrEmpty($("#roleName").val())) {
            swal("请输入角色名称", "", "warning")
            $("#roleName").focus();
            return false;
        }
        hotUtil.loading.show();
        hotUtil.ajaxCall("/sys/ajax/editrole", {
            roleId: parseInt($.trim($("#roleId").val())),
            roleName: $.trim($("#roleName").val())
        }, function (ret) {
            hotUtil.loading.close();
            if (ret.resultCode === 1) {
                rolesHandler.init();
                swal(ret.resultMsg, "", "success");
                $('#addRoleModal').modal('hide');
            }
            else {
                swal(ret.resultMsg, "", "error")
            }
        });
    },
    btnSubmitPower: function () {
        var self = this;
        if (hotUtil.isNullOrEmpty(self.authority) || self.authority.length <= 1) {
            swal("请勾选菜单权限", "", "warning");
            return;
        }
        var param = {
            roleId: parseInt($.trim($("#roleId_menu").val())),
            authority: self.authority
        };
        hotUtil.ajaxCall("/sys/ajax/setpower", param, function (ret) {
            hotUtil.loading.close();
            if (ret.resultCode === 1) {
                self.setModel(param.roleId, param.authority);
                swal("设置成功", "", "success");
                $('#addRolePowerModal').modal('hide');
            }
            else {
                swal("设置失败", "", "error")
            }
        });
    },
    /**
     * 设置权限
     */
    setPower: function (roleId) {
        var self = this;
        if (roleId > 0) {
            $("#roleId_menu").val(roleId);
            var data = this.getModel(roleId);
            if (data != null)
                self.authority = data.authority;
            if (self.authority == null)
                self.authority = "";
            var appendHtml = this.outputChild(0, self.authority);
            $("#menulist").html(appendHtml);
            $(".i-checks").iCheck({
                checkboxClass: "icheckbox_square-green",
                radioClass: "iradio_square-green",
            });
            $('.i-checks').on('ifChecked', function (event) {
                var itemCode = parseInt($(this).val());
                if (self.authority.indexOf("|" + itemCode + "|") < 0) {
                    self.authority += ("|" + itemCode + "|");
                    self.authority = self.authority.replace("||", "|");
                    self.parentChecked(itemCode);
                    self.childChecked(itemCode);
                }
            });
            $('.i-checks').on('ifUnchecked', function (event) {
                var itemCode = parseInt($(this).val());
                if (self.authority.indexOf("|" + itemCode + "|") >= 0) {
                    self.authority = self.authority.replaceAll("|" + itemCode + "|", "|");
                    self.childUnChecked(itemCode);
                }
            });
        }
        else {
            $('#myMenuModal').modal('hide');
        }
    },
    /**
     * 修改状态
     * @param roleId
     */
    setEnable: function (roleId) {
        var self = this;
        hotUtil.loading.show();
        hotUtil.ajaxCall("/sys/ajax/setenable", {
            roleId: roleId
        }, function (ret) {
            hotUtil.loading.close();
            if (ret.resultCode === 1) {
                self.init();
                swal("设置成功", "", "success");
            }
            else {
                swal(ret.resultMsg, "", "error")
            }
        });
    },
    /**
     * 取消当前节点的子节点的选中状态
     * @param itemCode
     */
    childUnChecked: function (itemCode) {
        var self = this;
        $.each(self.menuList, function (o, item) {
            if (item.itemParentCode === itemCode) {
                if (self.authority.indexOf("|" + item.itemCode + "|") >= 0) {
                    self.authority = self.authority.replaceAll("|" + item.itemCode + "|", "|");
                    $("#i-checks-" + item.itemCode + "").iCheck('uncheck');
                    self.childUnChecked(item.itemCode);
                }
            }
        });
    },
    /**
     * 选中当前节点的父节点的选中状态
     * @param itemCode
     */
    parentChecked: function (itemCode) {
        var self = this;
        $.each(self.menuList, function (o, item) {
            if (item.itemParentCode !== 0 && item.itemCode === itemCode) {
                if (self.authority.indexOf("|" + item.itemParentCode + "|") < 0) {
                    self.authority += ("|" + item.itemParentCode + "|");
                    self.authority = self.authority.replace("||", "|");
                    $("#i-checks-" + item.itemParentCode + "").iCheck('check');
                    self.parentChecked(item.itemParentCode);
                }
            }
        });
    },
    /**
     * 选中当前节点的子节点的选中状态
     */
    childChecked: function (itemCode) {
        var self = this;
        $.each(self.menuList, function (o, item) {
            if (item.itemParentCode === itemCode) {
                if (self.authority.indexOf("|" + item.itemCode + "|") < 0) {
                    self.authority += ("|" + item.itemCode + "|");
                    self.authority = self.authority.replace("||", "|");
                    $("#i-checks-" + item.itemCode + "").iCheck('check');
                    self.childChecked(item.itemCode);
                }
            }
        });
    },

    /**
     * 初始化菜单
     */
    initMenu: function () {
        var self = this;
        hotUtil.loading.show();
        hotUtil.ajaxCall("/sys/ajax/list", null, function (ret) {
            hotUtil.loading.close();
            if (ret.resultCode === 1) {
                self.menuList = ret.data;
            }
        });
    },
    getChildMenu: function (itemParentCode) {
        var resultList = [];
        $.each(this.menuList, function (o, item) {
            if (item.itemParentCode === itemParentCode) {
                resultList.push(item);
            }
        });
        return resultList;
    },
    /**
     * 递归输出菜单
     */
    outputChild: function (itemParentCode, authority) {
        var self = this;
        var data = self.getChildMenu(itemParentCode);
        var appendHtml = "";
        $.each(data, function (o, item) {
            var tempHtml = self.menusTemplate;
            if (authority.indexOf("|" + item.itemCode + "|") >= 0)
                tempHtml = tempHtml.replace(/{checked}/gm, "checked=\"checked\"");
            else
                tempHtml = tempHtml.replace(/{checked}/gm, "");
            tempHtml = tempHtml.replace(/{itemName}/gm, item.itemName);
            tempHtml = tempHtml.replace(/{itemCode}/gm, item.itemCode);
            tempHtml = tempHtml.replace(/{iconClsDom}/gm, hotUtil.isNullOrEmpty(item.itemIconCls) ? "" : "<i class=\"fa fa-" + item.itemIconCls + "\"></i>");//item.itemIconCls
            tempHtml = tempHtml.replace(/{itemFunction}/gm, item.itemFunction ? "功能" : "");
            var itemChildCount = item.itemChildCount;
            if (itemChildCount > 0) {
                tempHtml = tempHtml.replace(/{childMenus}/, self.outputChild(item.itemCode, authority));
                tempHtml = tempHtml.replace(/{collapse_expand}/, "<button  onclick=\"rolesHandler.collapse(this)\" data-action=\"collapse\" type=\"button\" style=\"display: block;\">关闭</button><button onclick=\"rolesHandler.expand(this)\" data-action=\"expand\" type=\"button\" style=\"display: none;\">展开</button>");
            }
            else {
                tempHtml = tempHtml.replace(/{childMenus}/, "");
                tempHtml = tempHtml.replace(/{collapse_expand}/, "");
            }
            appendHtml += tempHtml;
        });
        return appendHtml;
    },

    expand: function (obj) {
        $(obj).parent().children(".dd-list").show();
        $(obj).parent().children("button").show();
        $(obj).hide();
    },

    collapse: function (obj) {
        $(obj).parent().children(".dd-list").hide();
        $(obj).parent().children("button").show();
        $(obj).hide();

    }
}

